package com.resurvolution.kingcloudmusicspringboot.common.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Date;

@Component
@Slf4j
public class JwtUtil {

    @Value("${security.jwt.secret-key}")
    private  String jwtSecretKey;

    @Value("${security.jwt.expiration}")
    private  long jwtExpirationTime;

    /**
     * 生成密钥
     * @return
     */
    private SecretKey getSigningKey() {
        return Keys.hmacShaKeyFor(jwtSecretKey.getBytes(StandardCharsets.UTF_8));
    }

    /**
     * 创建jwt token
     */
    public String generateToken(Integer userId, int roleFlag) {
        String role;
        if (roleFlag == 1) {
            role = "ADMIN";
        } else if (roleFlag == 2) {
            role = "VIP";
        } else {
            role = "USER";
        }
        return Jwts
                .builder()
                .subject(String.valueOf(userId))
                .claim("userId", String.valueOf(userId))
                .claim("roles", role)
                .issuedAt(Date.from(Instant.now()))
                .expiration(Date.from(Instant.now().plusMillis(jwtExpirationTime)))
                .signWith(getSigningKey(), Jwts.SIG.HS256)
                .compact();
    }

    /**
     * 解析验证
     */
    public Claims parseToken(String token) {
        try {
            Jws<Claims> jws = Jwts.parser()
                    .verifyWith(getSigningKey())
                    .build()
                    .parseSignedClaims(token);

            Claims claims = jws.getPayload();

            if (claims.getExpiration().before(new Date())) {
                throw new JwtException("token已过期");
            }
            return claims;
        } catch (SignatureException | MalformedJwtException | UnsupportedJwtException | IllegalArgumentException e) {
            throw new JwtException("token无效");
        }

    }
}
